package com.joshua.newsdemo.utils;

import com.joshua.newsdemo.NewsBean;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * @description:
 * @author: JoshuaWong E-mail:joshuawongchn@gmail.com
 * @date: 2017年03月22日 11:35
 * @version: 1.0
 */

public class NewsFilter {
    public static NewsBean filt(String in) {
        NewsBean bean = new NewsBean();
        Document doc = Jsoup.parse(in);
        bean.setTitle(doc.title());
        Elements contents = doc.getElementsByTag("p");
        StringBuffer sb = new StringBuffer();
        for (Element e : contents) {
            sb.append(e.toString());
            sb.append("\n");
        }
        String html = sb.toString();
        html = html.replaceAll("src=\"../..", "src=\"http://news.xidian.edu.cn");
        html = imageProcess(html);
        bean.setHtml(html);
        return bean;
    }

    /**
     * 过滤图片的宽高属性
     *
     * @param in
     * @return
     */
    public static String imageProcess(String in) {
        Document doc = Jsoup.parse(in);
        Elements imgs = doc.getElementsByTag("img");
        for (Element img : imgs) {
            String src = img.attr("src");
            String value = String.format("javascript:mWebViewImageListener" +
                    ".showImagePreview('%s')", src);
            img.attr("width", "100%");
            img.attr("height", "auto");
            img.attr("onClick", value);
        }
        return doc.toString();
    }

}